﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Timers;
using System.Data.SqlClient;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using System.Collections.Generic;
using System.Text;
/// <summary>
///Class1 的摘要说明
/// </summary>

public class ScheduledTask
{

    private static readonly ScheduledTask _ScheduledTask = null;
    private System.Threading.Timer UpdateTimer = null;
    private System.Threading.Timer UpdateTimer2 = null;
    private int _IsRunning;//上一个时间间隔触发的任务是否运行完成  
    private int _IsRunning2;
    DataBase db = new DataBase();
    static ScheduledTask()
    {
        _ScheduledTask = new ScheduledTask();
    }

    public static ScheduledTask Instance()
    {
        return _ScheduledTask;
    }

    /// <summary>
    /// timer启动
    /// </summary>
    public void Start()
    {
        if (UpdateTimer == null)
        {
            //计算现在到目标时间要过的时间段。 
            DateTime LuckTime = DateTime.Now.Date.Add(new TimeSpan(12, 0, 0));//指定执行的时、分、秒 exp:每天17:30分执行,new TimeSpan(17, 30, 0)
            TimeSpan span = LuckTime - DateTime.Now;
            if (span < TimeSpan.Zero)
            {
                span = LuckTime.AddDays(1d) - DateTime.Now;
            }

            UpdateTimer = new System.Threading.Timer(new TimerCallback(UpdateTimerCallback), null, span, TimeSpan.FromTicks(TimeSpan.TicksPerDay));
        }

        if (UpdateTimer2 == null)
        {
            //计算现在到目标时间要过的时间段。 
            DateTime LuckTime = DateTime.Now.Date.Add(new TimeSpan(17, 0, 0));//指定执行的时、分、秒 exp:每天17:30分执行,new TimeSpan(17, 30, 0)
            TimeSpan span = LuckTime - DateTime.Now;
            if (span < TimeSpan.Zero)
            {
                span = LuckTime.AddDays(1d) - DateTime.Now;
            }

            UpdateTimer2 = new System.Threading.Timer(new TimerCallback(UpdateTimerCallback2), null, span, TimeSpan.FromTicks(TimeSpan.TicksPerDay));
        }

    }

    /// <summary>
    /// 时钟callback事件
    /// </summary>
    /// <param name="sender"></param>
    private void UpdateTimerCallback(object sender)
    {
        if (Interlocked.Exchange(ref _IsRunning, 1) == 0)
        {
            try
            {
                //要处理后台任务
                //TimeTask task = new TimeTask();
                //task.TimeTaskSendEmail();    
               // ISyAutoSendEmail autoEmail = new SyAutoSendEmail();
               // autoEmail.InsertEmailContent("add test", "this is a test", new string[1] { "ruanpeng8@163.com" }, 18);
               // autoEmail.TimeTaskSendEmail();
                TimeTaskSendEmail();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                Interlocked.Exchange(ref _IsRunning, 0);
            }
        }
    }

    private void UpdateTimerCallback2(object sender)
    {
        if (Interlocked.Exchange(ref _IsRunning2, 1) == 0)
        {
            try
            {
                //要处理后台任务
                //TimeTask task = new TimeTask();
                //task.TimeTaskSendEmail();    
               // ISyAutoSendEmail autoEmail = new SyAutoSendEmail();
                TimeTaskSendEmail();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                Interlocked.Exchange(ref _IsRunning2, 0);
            }
        }
    }


    /// <summary>
    ///timer停止
    /// </summary>
    public void Stop()
    {
        if (UpdateTimer != null)
        {
            UpdateTimer.Dispose();
            UpdateTimer = null;
            UpdateTimer2 = null;
        }
    }

    //DataBase db = new DataBase();

    public void TimeTaskSendEmail()
    {
        //提取需要发送的distinct email集合

        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@Status", "0");
        string sqlStr = @"select distinct Email from Sy_Recipient as SR inner join Sy_PendingMail as SPM on SR.PendingMailID=SPM.PKID
                              where SR.Status=@Status ";
        DataTable dt = db.RunSqlTab(sqlStr, parms);
        if (dt != null && dt.Rows.Count > 0)
        {
            SqlParameter[] parmsE = new SqlParameter[2];
            DataTable dtC = new DataTable();
            StringBuilder strB = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)//循环Email集合,把需要发到该email下的邮件内容合起来,并发送.
            {
                if (StringUtil.IsEmailAddress(dt.Rows[i]["Email"].ToString()))
                {
                    parmsE[0] = new SqlParameter("@Status", "0");
                    parmsE[1] = new SqlParameter("@Email", dt.Rows[i]["Email"].ToString());
                    sqlStr = @"select SPM.*,SR.Status,SR.Email from Sy_PendingMail as SPM inner join Sy_Recipient as SR on SR.PendingMailID=SPM.PKID
                                    where Status=@Status and Email=@Email ";
                    dtC = db.RunSqlTab(sqlStr, parmsE);

                    if (dtC != null && dtC.Rows.Count > 0)//把发到同一email下的Email内容集合起来
                    {
                        string title = @"Hello, [title]: 


some reminds from special-line,

";
                        title = title.Replace("[title]", dt.Rows[i]["Email"].ToString());
                        strB.Append(title);
                        for (int j = 0; j < dtC.Rows.Count; j++)
                        {
                            strB.Append(dtC.Rows[j]["App"].ToString());
                            // strB.Append(@"\r\n");
                            strB.Append(dtC.Rows[j]["Content"].ToString());
                        }

                        //发送
                        string subject = "reminds from special-line!";

                        try
                        {
                            SendMail send = new SendMail();
                            string content = strB.ToString();
                            send.MailBody = content;
                            send.MailSubject = subject;
                            send.MailTo = dt.Rows[i]["Email"].ToString();                            
                            send.Send();

                            //发送成功后修改状态
                            SqlParameter[] parmsU = new SqlParameter[3];
                            parmsU[0] = new SqlParameter("@Status", "1");
                            parmsU[1] = new SqlParameter("@Email", dt.Rows[i]["Email"].ToString());
                            parmsU[2] = new SqlParameter("@SendTime", DateTime.Now);
                            sqlStr = "update Sy_Recipient set Status=@Status,SendTime=@SendTime where Email=@Email";
                            db.ExecSqlTransaction(sqlStr, parmsU);

                        }
                        catch (Exception e)
                        {
                            //SqlParameter[] eparms = new SqlParameter[4];
                            //eparms[0] = new SqlParameter("@Content", e.Message);
                            //eparms[1] = new SqlParameter("@App", "test");
                            //eparms[2] = new SqlParameter("@AddTime", DateTime.Now);
                            //eparms[3] = new SqlParameter("@Creater", "18");
                            //string sqlStsrs = @"INSERT INTO Sy_PendingMail(App,AddTime,Creater,Content) VALUES(@App,@AddTime,@Creater,@Content)";
                            //db.ExecSqlTransaction(sqlStsrs, eparms);
                        }
                        finally
                        {
                            strB.Remove(0, strB.ToString().Length);
                        }
                    }
                }
            }
        }
    }

}

